#pragma once

#include <iostream>
#include <unordered_map>
#include <fstream>
#include <string>
#include "Log.hpp"

namespace dict
{
    const std::string defaultpath = "./Dict.txt";
    const std::string sep = ": ";

    class Dict
    {
    private:
        bool Load()
        {
            std::ifstream in(_dict_filepath);
            if (!in.is_open())
            {
                LOG(FATAL, "open %s error\n", _dict_filepath.c_str());
                return false;
            }

            std::string line;
            while (std::getline(in, line))
            {
                // 若为空行，退出当前循环
                if (line.empty())
                {
                    continue;
                }
                // 找到分隔符所在位置
                auto pos = line.find(sep); // abcd: efg
                // 没找到则退出当前循环
                if (pos == std::string::npos)
                {
                    continue;
                }
                // 找到单词，左闭右开区间[...)
                std::string word = line.substr(0, pos);
                if (word.empty())
                {
                    continue;
                }
                // 找到汉语翻译
                std::string han = line.substr(pos + sep.size());
                if (han.empty())
                {
                    continue;
                }
                LOG(DEBUG, "load 信息,%s: %s\n", word.c_str(), han.c_str());
                _dict.insert(std::make_pair(word, han));
            }
            // 关闭文件
            in.close();
            LOG(DEBUG, "load %s 成功\n", _dict_filepath.c_str());

            return true;
        }

    public:
        Dict(const std::string &path = defaultpath)
            : _dict_filepath(path)
        {
            Load();
        }

        // 翻译
        std::string Translate(const std::string &word, bool ok)
        {
            ok = true;
            auto iter = _dict.find(word);
            if (iter == _dict.end())
            {
                ok = false;
                return "没找到";
            }

            return iter->second;
        }

        ~Dict()
        {
        }

    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_filepath;
    };
}